package netty.rpc.framework.core.netty.transport.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import netty.rpc.framework.core.netty.transport.protocol.RPCMessage;
import netty.rpc.framework.core.netty.transport.serializer.Serializer;
import netty.rpc.framework.core.netty.transport.serializer.impl.DefaultSerializer;
import netty.rpc.framework.core.netty.transport.serializer.impl.KryoSerializer;

import java.util.List;

/**
 * @author guiyiqiao
 * @date 2020/12/3
 *
 * Netty的解码器，将 byte 数据解码为RPCMessage
 */

@Slf4j
public class Byte2RPCMessageDecoder extends ByteToMessageDecoder {

    private Serializer serializer = new KryoSerializer();
    /**
     * 使用于接收端RPCMessage消息的解码,使用header+content格式
     * @param channelHandlerContext
     * @param byteBuf
     * @param list
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if(byteBuf.readableBytes() < 4){
            return;
        }
        byteBuf.markReaderIndex();
        int len = byteBuf.readInt();
        if(byteBuf.readableBytes() < len){
            byteBuf.resetReaderIndex();
            return;
        }
        int position = 0;
        ByteBuf buf = byteBuf.readBytes(len);
        byte[] bytes = new byte[len];
        buf.readBytes(bytes);
        log.info("byte = ",bytes.toString());
        RPCMessage message = serializer.deserialize(bytes,RPCMessage.class);
        log.info("message = {}",message.toString());
        list.add(message);
    }
}
